import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/scheduler.dart';
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
import 'package:encrypt/encrypt.dart' as mykey;
import 'package:get/get.dart';

class SecureStorageService extends GetxService {
  static SecureStorageService get instance => Get.find();

  final FlutterSecureStorage _storage = const FlutterSecureStorage();
  late mykey.Encrypter _encrypter;
  final String _encryptionKeyName = 'app_encryption_key';
  final String _ivSuffix = '_iv';

  Future<SecureStorageService> init() async {
    try {
      // 初始化加密器
      final key = await _getOrCreateEncryptionKey();
      _encrypter = mykey.Encrypter(mykey.AES(mykey.Key.fromBase64(key)));
      return this;
    } catch (e) {
      _handleSecurityError(e);
      rethrow;
    }
  }

  Future<String> _getOrCreateEncryptionKey() async {
    String? existingKey = await _storage.read(key: _encryptionKeyName);
    if (existingKey == null) {
      final newKey = mykey.Key.fromSecureRandom(32).base64;
      await _storage.write(key: _encryptionKeyName, value: newKey);
      return newKey;
    }
    return existingKey;
  }

  Future<void> write(String key, String value) async {
    try {
      final iv = mykey.IV.fromSecureRandom(16);
      final encrypted = _encrypter.encrypt(value, iv: iv);

      // 存储加密数据和IV
      await Future.wait([
        _storage.write(key: key, value: encrypted.base64),
        _storage.write(key: _ivKey(key), value: iv.base64),
      ]);
    } catch (e) {
      _handleSecurityError(e);
      rethrow;
    }
  }

  Future<String?> read(String key) async {
    try {
      final encrypted = await _storage.read(key: key);
      final ivBase64 = await _storage.read(key: _ivKey(key));

      if (encrypted == null || ivBase64 == null) return null;

      return _encrypter.decrypt64(
        encrypted,
        iv: mykey.IV.fromBase64(ivBase64),
      );
    } catch (e) {
      _handleSecurityError(e);
      return null;
    }
  }

  String _ivKey(String key) => '$key$_ivSuffix';

  void _handleSecurityError(dynamic error) {
    debugPrint('[SECURITY ERROR] ${DateTime.now()}: $error');
    SchedulerBinding.instance.addPostFrameCallback((_) {
      if (Get.isSnackbarOpen) return;

      Get.snackbar(
        '安全警告',
        '安全存储操作失败',
        duration: const Duration(seconds: 3),
        snackPosition: SnackPosition.BOTTOM,
        backgroundColor: Colors.red.withOpacity(0.8),
      );
    });
  }

  Future<void> delete(String key) async {
    await Future.wait([
      _storage.delete(key: key),
      _storage.delete(key: _ivKey(key)),
    ]);
  }
}